<?php

namespace App\Models;

use App\Util\Tool;
use App\Util\Url;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Article extends Model
{

    protected $table = 'c_articles';
    protected $guarded = [];
    public function doctor()
    {
        return $this->hasOne('App\Models\Doctor', 'id', 'doctor_id');
    }

    public function relate_article()
    {
        return $this->hasMany('App\Models\WorkRelateArticle');
    }

    /**
     * 删除数据
     */
    protected static function boot()
    {
        parent::boot();
        // 在删除用户时执行
        static::deleting(function ($user) {
            // 删除与用户关联的文章
            $user->relate_article()->delete();
            (new CourseCollect())->where([['type', '=', 3], ['course_id', '=', $user->id]])->delete();
            (new Footprint())->where([['goods_id', '=', $user->id], ['type', '=', 3]])->delete();
        });
    }

    /****
     * @param $param
     * @return mixed
     * 文章列表
     */
    public function getList($param)
    {
        $work_article = (new WorkRelateArticle());
        $field = "c_work_relate_articles.id";
        $asc = "desc";
        $where = [];
        if (isset($param['work_id']) && !empty($param['work_id'])) {  //医护室
            $where[] = ['c_work_relate_articles.work_id', '=', $param['work_id']];
        }
        if (isset($param['types']) && !empty($param['types'])) {    //分类id
            $where[] = ['c_articles.art_types', '=', $param['types']];
        }
        if (isset($param['cate_id']) && !empty($param['cate_id'])) {    //分类id
            $where[] = ['c_work_relate_articles.cate_id', '=', $param['cate_id']];
        }
        if (isset($param['title']) && !empty($param['title'])) {  //标题
            $where[] = ['c_articles.article_title', 'like', '%' . $param['title'] . '%'];
        }
//        $where[] = ['c_courses.course_category_id', '=', $param['category_id']];
        $res = $work_article->join('c_doctor_works', 'c_doctor_works.id', '=', 'c_work_relate_articles.work_id')
            ->select("c_articles.*")
            ->addSelect("c_doctor_works.work_name")
            ->addSelect("c_work_relate_articles.id as art_relate_id","c_work_relate_articles.work_id as work_id")
            ->join('c_articles', 'c_articles.id', '=', 'c_work_relate_articles.article_id')
            ->orderBy($field, $asc)
            ->where($where)
            ->simplePaginate();
        if (!empty($res)) {
            $list = $res->toArray();
            $doctor = new Doctor();
            $host = new Url();
            foreach ($list['data'] as $k => $val) {
                if (!empty($val['art_img'])) {
                    $list['data'][$k]['art_img'] =$host::getHttpHost() . 'upload/' . $val['art_img'];
                }
                if (!empty($val['sound'])) {
                    $list['data'][$k]['sound'] = $host::getHttpHost() . 'upload/' . $val['sound'];
                }
                $doc  = $doctor::where([['id','=',$val['doctor_id']]])->first();
                if($doc){
                    $doc->profile = $host::getHttpHost() . 'upload/' .$doc->profile;
                    $list['data'][$k]['doctor'] = $doc->toArray();
                }else{
                    $list['data'][$k]['doctor'] = [];
                }
                $list['data'][$k]['time'] = date("Y-m-d",strtotime($val['created_at']));
                $list['data'][$k]['content'] = strip_tags(str_replace("&nbsp;",'',$val['content']));//strip_tags($val['content']);
//                if (!empty($val['course_images'])) {
//                    $images = json_decode($val['course_images']);
//                    $img_data = [];
//                    if (is_array($images)) {
//                        foreach ($images as $kk => $vv) {
//                            $img_data[] = env('APP_URL') . '/' . $vv;
//                        }
//                    } else {
//                        $img_data[] = env('APP_URL') . '/' . $val['course_images'];
//                    }
//                    $list['data'][$k]['course_images'] = $img_data;
//                }
            }
            return $list;
        }
        return [];

//        $field = "id";
//        $asc = "asc";
//        $where = [];
//        $page = isset($param['page']) && !empty($param['page']) ? $param['page'] : 1;
//        if (isset($param['score']) && !empty($param['score'])) {  //评价
//            if ($param['score'] == 1) {//倒序
//                $field = "course_score";
//                $asc = "asc";
//            } else {
//                $field = "course_score";
//                $asc = "desc";
//            }
//        }
//        if (isset($param['sales']) && !empty($param['sales'])) {  //销量
//            if ($param['sales'] == 1) {//倒序
//                $field = "buy_num";
//                $asc = "asc";
//            } else {
//                $field = "buy_num";
//                $asc = "desc";
//            }
//        }
//        if (isset($param['price']) && !empty($param['price'])) {  //价格
//            if ($param['price'] == 1) {//倒序
//                $field = "course_price";
//                $asc = "asc";
//            } else {
//                $field = "course_price";
//                $asc = "desc";
//            }
//        }
//        if (isset($param['isfee']) && !empty($param['isfee']) ) {  //是否收费
//            $where[] = ['isfee', '=', $param['isfee']];
//        }
//        if (isset($param['work_id']) && !empty($param['work_id'])) {  //医护室
//            $where[] = ['work_id', '=', $param['work_id']];
//        }
//        if (isset($param['types']) && !empty($param['types'])) {  //分类id
//            $where[] = ['art_types', '=', $param['types']];
//        }
//        if (isset($param['is_use']) && !empty($param['is_use'])) {  //是否使用
//            $where[] = ['is_use', '=', $param['is_use']];
//        }
//        if (isset($param['title']) && !empty($param['title'])) {  //标题
//            $where[] = ['course_title', 'like', '%' . $param['title'] . '%'];
//        }
//        $result =  $this->where($where)->orderBy($field, $asc)->paginate(15, ['*'], 'page', $page);
//        if(!empty($result)){
//            return $result->toArray();
//        }
//        return [];
    }



    /****
     * @param $filter
     * @return mixed
     * 客户端文章详情
     */
    public function getArticleInfo($data)
    {
        $relate_art = new WorkRelateArticle();
        $likes = new Like();
//        $info = $relate_art::getInfoById($data['art_relate_id']);
        if(isset($data['is_app'])){ //app调用浏览量加一
            $this->where('id', $data['article_id'])->increment('views', 1);
        }
        $article = $this->where("id", '=', $data['article_id'])->first();
        if(empty($article)){
            return null;
        }
        $article = $article->toArray();
        $article['is_like'] = 0;
        $article['is_collect'] = 0;
        if (isset($data['user_id']) && isset($data['work_id'])) {
            $like = $likes->where([['user_id', '=', $data['user_id']], ["article_id", "=", $data['article_id']]])->first();
            if ($like) {
                $article['is_like'] = 1;
            }
            $col = (new CourseCollect())
                ->where([['course_id', '=', $data['article_id']], ['type', '=', 3], ['collect_type', '=', 1],['user_id','=',$data['user_id']]])
                ->count("id");
            if($col>0){
                $article['is_collect'] = 1;
            }
            (new VisitUser())->where([['type','=',2],['user_id','=',$data['user_id']],['patient_type','=',1],['patient_id','=',$data['article_id']]])->update(['is_read'=>0]);
        }
        $article['collect_num'] = (new CourseCollect())
            ->where([['course_id', '=', $data['article_id']], ['type', '=', 3], ['collect_type', '=', 1]])
            ->count("id");
        if (!empty($article['art_img'])) {
            $article['art_img'] = env('APP_URL') . '/upload/' . $article['art_img'];
        }
        if (!empty($article['sound'])) {
            $article['sound'] = env('APP_URL') . '/upload/' . $article['sound'];
        }
        $doc = (new Doctor())->where([['id', '=', $article['doctor_id']]])->first();
        if(!empty($doc)){
            $doc->profile = env('APP_URL') . '/upload/' . $doc->profile;
            $article['doctor'] = $doc;
        }else{
            $article['doctor'] = [];
        }
        return $article;
    }

    
    /***
     * 
     * 文章详情工作室端
     */
    public function getArticleInfoForDoctory($filter)
    {
        $res = $this->with(['doctor'])->where([['id', '=', $filter['id']]])->first();
        $this->where([['id', '=', $filter['id']]])->increment("views",1);
        $res->art_img = Url::getHttpHost() . 'upload/' . $res->art_img;
        $res->sound = Url::getHttpHost() . 'upload/' . $res->sound;
        $res->add_time = date("Y-m-d", strtotime($res->created_at));
        if ($res->doctor) {
            $res->doctor->profile = Url::getHttpHost() . "upload/" . $res->doctor->profile;
        }
        $res->collect_num = (new CourseCollect())
            ->where([['course_id', '=', $filter['id']], ['type', '=', 3], ['collect_type', '=', 2]])
            ->count("id");
        $res->is_cllo = 0;
        $res->is_selected = 0;
        if (isset($filter['doctor_id'])) {
            $clos = (new CourseCollect())
                ->where([['course_id', '=', $filter['id']], ['type', '=', 3], ['collect_type', '=', 2], ['user_id', '=', $filter['doctor_id']]])
                ->first();
            if ($clos) {
                $res->is_cllo = 1;
            }
        }
        //判断是否是工作室的文章包括已选文章
        $is_selected = (new WorkRelateArticle())->where([['article_id', '=', $filter['id']], ['work_id', '=', $filter['work_id']]])->first();
        if ($is_selected) {
            $res->is_selected = 1;
        }
        if (!empty($res)) {
            return $res->toArray();
        }
        return [];
    }


    /**
     * @param $filter
     * 添加文章关联
     */
    public function addRelateArticles($filter)
    {
        $article_ids = Tool::handelString($filter['article_ids']);
        if (empty($article_ids)) {
            return "文章ID不能为空";
        }
        $relate = new WorkRelateArticle();
        $data = [];
        $log = new SelectedGoodsLog();
        foreach ($article_ids as $k => $v) {
            $relate->where([['article_id', '=', $v], ['work_id', '=', $filter['work_id']]])->delete();
            $log::where([['goods_id','=',$v],['work_id','=',$filter['work_id']],['type','=',3]])->delete();
            $data[$k]['article_id']  = $v;
            $data[$k]['work_id']  = $filter['work_id'];
            $data[$k]['cate_id']  =  $filter['cate_id'];
            $data[$k]['created_at']  =  date("Y-m-d H:i:s",time());
            $data[$k]['updated_at']  =  date("Y-m-d H:i:s",time());
        }
        $yes = DB::table('c_work_relate_articles')->insert($data);
        if($yes){
            return true;
        }
        return "添加失败";
    }

    /***
     *
     * 公益库
     */
    public function getAllArticleList($param)
    {
        $where[] = ['status','=',1];
        $where[] = ['is_use','=',1];
        $where[] = ['is_share','=',1];
        $field = "id";
        $sort = "desc";
        //查看工作室已有公益文章
        $ids = (new WorkRelateArticle())::getArticleIds($param);
        $selected_ids = (new SelectedGoodsLog())::getSelectedArticleIds($param,3);
        if (!empty($selected_ids)) {
            $selected_ids = $selected_ids->toArray();
        } else {
            $selected_ids = [];
        }
        if (isset($param['clinic_cate_id'])) { //分类id
            $where[] = ['clinic_cate_id', '=', $param['clinic_cate_id']];
        }
        if (isset($param['is_original'])) {  //文章类型
            $where[] = ['is_original', '=', $param['is_original']];
        }
        if (isset($param['title'])) {  //标题搜索
            $where[] = ['article_title', 'like', '%' . $param['title'] . '%'];
        }
        if (isset($param['work_id'])) {  //标题搜索
            $where[] = ['work_id', '!=', $param['work_id']];
        }

        if (isset($param['hot']) && $param['hot'] == 1) { //热度
            $field = "views";
            $sort = "desc";
        } elseif (isset($param['hot']) && $param['hot'] == 2) {
            $field = "views";
            $sort = "asc";
        }
//        ->select("id","article_title","views","likes","status","art_img","is_share","self_cateid","work_id",
//        "is_original","clinic_cate_id","doctor_id","art_types","sound","author","is_use","isfee")
        $res = $this->where($where)->whereNotIn('id', $ids)->orderBy($field, $sort)->simplePaginate();
        if (!empty($res)) {
            $result = $res->toArray();
            $host = new  Url();
            $doctor = new Doctor();
            $relate = new WorkRelateArticle();
            foreach ($result['data'] as $k => &$v) {
                if (in_array($v['id'], $selected_ids)) {
                    $v['selected'] = 1;
                } else {
                    $v['selected'] = 0;
                }
                $v['use_count'] = $relate->where([['article_id','=',$v['id']]])->count("id");
                $v['art_img'] = $host::getHttpHost() . 'upload/' . $v['art_img'];
                $v['doctor_name'] =$doctor->where([['id','=',$v['doctor_id']]])->value("real_name");
                $v['content'] = strip_tags(str_replace("&nbsp;",'',$v['content']));;//strip_tags($v['content']);
            }
            return $result;
        }
        return [];
    }


    /**
     * @param $param
     * 科普发布文章
     */

    public function addArticle($data)
    {
        try {
            DB::beginTransaction(); // 开始事务
//                更新
            if (isset($data['id']) && !empty($data['id'])) {
                $redata = $this->getInfo($data['id']);
                $redata->doctor_id = isset($data['doctor_id']) ? $data['doctor_id'] : $redata->doctor_id;
                $redata->work_id = isset($data['work_id']) ? $data['work_id'] : $redata->work_id;
                $redata->article_title = isset($data['article_title']) ? $data['article_title'] : $redata->article_title;
                $redata->content = isset($data['content']) ? $this->handelContentImage($data['content']) : $redata->content;
                $redata->is_original = isset($data['is_original']) ? $data['is_original'] : $redata->is_original;
                $redata->art_img = isset($data['art_img']) ? $data['art_img'] : $redata->art_img;
                $redata->is_use = isset($data['is_use']) ? $data['is_use'] : $redata->is_use;
                $redata->status = 1;
                $redata->is_share = isset($data['is_share']) ? $data['is_share'] : $redata->is_share;
                $redata->clinic_cate_id = isset($data['clinic_cate_id']) ? $data['clinic_cate_id'] : $redata->clinic_cate_id;
                $redata->art_types = isset($data['art_types']) ? $data['art_types'] : $redata->art_types;
                $this->addWorkRelateArticles($data,$data['id']);
                $res = $redata->save();
            } else {
                //添加
                $this->doctor_id = $data['doctor_id'];
                $this->work_id = $data['work_id'];
                $this->article_title = $data['article_title'];
                $this->content = $this->handelContentImage($data['content']);
                $this->is_original = isset($data['is_original']) ? $data['is_original'] : 1;
                $this->art_img = isset($data['art_img']) ? $data['art_img'] : "";
                $this->is_share = isset($data['is_share']) ? $data['is_share'] : 0;
                $this->status = 1;
                $this->clinic_cate_id = $data['clinic_cate_id'];
                $this->author = (new Doctor())->where([['id','=',$data['doctor_id']]])->value("real_name");
                $this->art_types = isset($data['art_types'])?$data['art_types']:1;
                $res = $this->save();
                GrowthNumberLog::add($data,11);
//                添加自己的分类
                $this->addWorkRelateArticles($data,$this->id);
            }
            if ($res) {
                DB::commit(); // 提交事务
                return true;
            } else {
                return '添加失败';
                DB::rollback(); // 回滚事务
            }
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }


    /**
     * @param $content
     * 处理内容中的图片路径
     */
    public function handelContentImage($content)
    {
        $matched = strstr($content, "upload/");
        if (!$matched) {
            return $content;
        }
        $uri = Url::getHttpHost() . 'upload/';
        return str_replace("upload/", $uri, $content);
    }

    /**
     * @param $data
     * @param $art_id
     * @return bool
     * 添加文章关联自己工作室的分类
     */
    public function addWorkRelateArticles($data, $art_id)
    {
        $relate = new WorkRelateArticle();
        $res = $relate->where([['work_id', '=', $data['work_id']], ['article_id', '=', $art_id]])->first();
        if ($res) {
            if ($res->cate_id != $data['self_cate_id']) { //分类ID不同,修改分类
                $res->cate_id = $data['self_cate_id'];
                return $res->save();
            }
            return true;
        }
        //添加
        $relate->cate_id = $data['self_cate_id'];
        $relate->work_id = $data['work_id'];
        $relate->article_id = $art_id;
        return $relate->save();
    }

    /**
     * @param $id
     * @return mixed
     * 获取文章详情
     */
    public function getInfo($id)
    {
        return $this->where([['id', '=', $id]])->first();
    }

    /***
     * 医师端获取我的文章
     */
    public function getMyArticles($param)
    {
        $host = new Url();
        $relate = new WorkRelateArticle();
        $whereor = [];
        $where = [];
        $field = "id";
        $sort = "desc";
        //科室赛选
        if (isset($param['clinic_cate_id'])) {
            $where[] = ["clinic_cate_id", '=', $param['clinic_cate_id']];
        }
        if (isset($param['views']) && $param['views'] ==1) {
            $field = "views";
            $sort = "desc";
        }elseif (isset($param['views']) && $param['views'] ==0){
            $field = "views";
            $sort = "asc";
        }
        $article_ids   = $relate->from("c_work_relate_articles as relate_article")
            ->join("c_articles as article",'article.id','=','relate_article.article_id')
            ->where($where)
            ->where([['relate_article.work_id','=',$param['work_id']]])
            ->pluck("relate_article.article_id");
        if (!empty($article_ids)) {
            $whereor[] = [function ($query) use ($article_ids) {
                return $query->whereIn('id', $article_ids);
            }];
        }
        $where[] = ['doctor_id', '=', $param['doctor_id']];
        $doc = new Doctor();
        $res = $this->where($where)->orWhere($whereor)->distinct()->orderBy($field, $sort)->simplePaginate()->toArray();
        if (!empty($res['data'])) {
            foreach ($res['data'] as $k => &$v) {
                if($v['art_img']){
                    $v['art_img'] = !empty( $v['art_img'])? $host::getHttpHost() . 'upload/' . $v['art_img']:"";
                }
                $v['count_doc']= $relate->where([['article_id', '=', $v['id']]])->count("id");
                $v['doc_name'] = $doc->where('id', $v['doctor_id'])->value("real_name");
                $v['content'] = strip_tags(str_replace("&nbsp;",'',$v['content']));
            }
        }
        return $res;
    }


    /**
     * @param $param
     *删除我的
     */
    public function delMyArticles($param)
    {
        $res = $this->getInfo($param['article_id']);
        if (empty($res)) {
            return "改文章不存在!";
        }
        if ($res->doctor_id != $param['doctor_id']) {
            (new WorkRelateArticle())->where([['article_id','=',$param['article_id']],['work_id','=',$param['work_id']]])->delete();
            return true;
        }
        $data = $this::destroy($param['article_id']);
        if ($data) {
            (new WorkRelateArticle())->where([['article_id','=',$param['article_id']]])->delete();
            (new CourseCollect())->where([['type','=',3],['course_id','=',$param['article_id']]])->delete();
            return true;
        }
        return "删除失败!";
    }


}
